# 获取/关闭浏览器驱动的类
import logging
import time

from base.base_delete_file import clear_file
from selenium import webdriver
from selenium.webdriver import ChromeOptions
from webdriver_manager.chrome import ChromeDriverManager

from base.base_logging import set_log_config


class BaseDriver(object):
    __driver = None
    __switch = False
    __flag = 0
    __save_cookie = None
    __token = None

    # 获取浏览器驱动
    @classmethod
    def get_driver(cls):
        if cls.__flag == 0:
            clear_file()
            set_log_config()
            cls.__flag += 1
        if cls.__driver is None:
            logging.info("creat chrome driver")
            """模式1：无界面模式"""
            # option = ChromeOptions()# 设置options参数，以开发者模式运行
            # option.add_experimental_option("excludeSwitches", ["enable-automation"])
            # option.add_argument('--no-sandbox')# 设置无界面运行
            # option.add_argument('--disable-dev-shm-usage')
            # option.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
            # option.add_argument('--hide-scrollbars')  # 隐藏滚动条, 应对一些特殊页面
            # option.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
            # option.add_argument('--headless')  # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
            # cls.__driver = webdriver.Chrome(ChromeDriverManager().install(), options=option)# 创建一个driver对象，模拟开启浏览器
            # """模式2：有界面模式"""
            cls.__driver = webdriver.Chrome()

            cls.__driver.maximize_window()  # 放大浏览器
            cls.__driver.implicitly_wait(10)  # 隐式等待
        else:
            logging.info("use existed chrome driver")
        return cls.__driver

    # 关闭浏览器驱动
    @classmethod
    def quit_driver(cls):

        if cls.__driver is not None and cls.__switch is False:
            time.sleep(1.5)
            # logging1.info("quit chrome driver")
            cls.__driver.quit()
            cls.__driver = None
            pass
        else:
            logging.info("chrome driver is still alive")

    # 开关
    @classmethod
    def set_switch(cls, switch):
        cls.__switch = switch

    # 获取cookie
    # @classmethod
    # def get_login_cookie(cls):
    #     cls.__save_cookie=cls.__driver.get_cookies()

    # 增加cookie
    # @classmethod
    # def add_cookie(cls):
    #     print(cls.__save_cookie)
    # for cookie in cls.__save_cookie:
    #     cls.__driver.add_cookie(cookie)

    # @classmethod
    # def get_token(cls):
    #     cls.__token=cls.__driver.execute_script('return localStorage.getItem("token")')
    #
    # @classmethod
    # def add_token(cls):
    #     print(cls.__token)
    #     time.sleep(3)
    #     js='localStorage.setItem("token","{}")'.format(cls.__token)
    #     cls.__driver.execute_script(js)
    #     time.sleep(3)
    #     cls.__driver.back()
    #     time.sleep(1)
